app.controller('CarCtrl', ['$scope', 'GoodsService', function($scope,GoodsService){
	
	// 从服务中获取所有商品的数据
	$scope.goods = GoodsService.allGoods();
	// console.log($scope.goods);
	$scope.goods.map(function(item){
		item.checked = true;
	});

	//计算商品总价
	function calcAllPrice(){
		$scope.allPrice = 0;
		$scope.goods.map(function(item){
			(item.checked == true) && ($scope.allPrice += item.price * item.count);
		});
	};
	calcAllPrice();

	//是否添加到购物车中
	$scope.addOrReduceToCart = function(){
		this.carGood = !this.carGood.checked;
		calcAllPrice();

		var f = false;
		$scope.goods.map(function(item){
			if(item.checked == false){
				f = true;
			}
		});
		if(f==true){
			$scope.allGoods = false;
		}else{
			$scope.allGoods = true;
		}
	};

	//勾选全部商品添加到购物车
	$scope.allGoods = true;
	$scope.addAllGoodsToCart = function(){
		//设置所有为添加
		$scope.goods.map(function(item){
			item.checked = true;
		});
		//重新计算价格
		calcAllPrice();
		//修改自身的样式
		$scope.allGoods = true;
	};

	//减少商品数量
	$scope.reduce = function(){
		if(this.carGood.count != 1){
			this.carGood.count--;
		}else{
			this.carGood.count = 0;
		}
		calcAllPrice();
		GoodsService.reduceCount(this.carGood);
		console.log(this);
	}

	//增加商品数量
	$scope.add = function(){
		this.carGood.count++;
		GoodsService.addGood(this.carGood);
		calcAllPrice();
	}

}])